package com.innovation.chengzhangriji.ui.agent;

import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Parent;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.AllBabyResponse;
import com.innovation.chengzhangriji.http.Auth;
import com.innovation.chengzhangriji.http.BabyAllResponse;
import com.innovation.chengzhangriji.http.BabyResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.NewMessageResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.ChZhRJFragment;
import com.innovation.chengzhangriji.ui.CreateActivity;
import com.innovation.chengzhangriji.ui.HomeActivity;
import com.innovation.chengzhangriji.ui.adapter.HomePageAdapter;
import com.innovation.chengzhangriji.ui.event.BaseEvent;
import com.orhanobut.logger.Logger;

import java.lang.ref.SoftReference;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import de.greenrobot.event.EventBus;

public class HomeActivityAgent {

    private SoftReference<HomeActivity> context;

    public HomeActivity getContext() {
        return context.get();
    }

    public HomeActivityAgent(HomeActivity context) {
        this.context = new SoftReference<HomeActivity>(context);
    }

    public void onResume() {
        // 上传小米推送 TOKEN
        updateMiPushToken();
    }

    /**
     * 获取所有宝宝信息
     */
    public Baby[] getAllBabyList() {
        if(getContext() == null) {
            return new Baby[0];
        }
        LoginInfo loginInfo = Config.getLoginInfo(getContext());
        if(loginInfo == null) {
            // 提示重新登录
            getContext().showLogoutDialog();
            return new Baby[0];
        }
        return DatabaseManager.getInstance(getContext()).queryBabyAll(loginInfo.getUserID());
    }

    /**
     * 从网络获取所有宝宝的信息
     */
    public void requestAllBabyInfo() {
        Config.startGetAllBabyInfoService(getContext());
    }

    /**
     * 获取最新通知
     */
    public void requestNewNotification() {
        final LoginInfo loginInfo = Config.getLoginInfo(getContext());
        if(loginInfo == null) {
            return;
        }
        final String userId = loginInfo.getUserID();
        final String phone = loginInfo.getPhone();
        final String token = loginInfo.getToken().getAccessToken();
        final long serverTS = DatabaseManager.getInstance(getContext()).queryMessageServerTS(userId);

        // 判断是否有新的申请和邀请消息
        Client.requestNewMessage(getContext(), phone, token, 0, serverTS, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                NewMessageResponse response = get(value.toString(), NewMessageResponse.class);
                if (response == null) {
                    return;
                }
                if (response.getServerTS() > serverTS) {
                    Logger.d("有新消息, newServerTs:" + response.getServerTS()+", oldServerTs:"+ serverTS);
                    Client.requestAllBaby(getContext(), phone, token, new ResponseHandler() {

                        @Override
                        public void onInnovationSuccess(JsonElement value) {
                            Logger.d("有新消息,获取所有宝宝信息成功");
                            AllBabyResponse response = get(value.toString(), AllBabyResponse.class);
                            if (response == null) {
                                return;
                            }
                            int length = response.getData().length;
                            int[] childIDArray = new int[length];
                            Auth[] auth = new Auth[length];
                            for (int i = 0; i < length; i++) {
                                childIDArray[i] = response.getData()[i].getId();
                                auth[i] = response.getData()[i].getAuth();
                            }
                            insertOrReplaceInTxBabyAndParent(userId, auth, childIDArray);
                            insertOrReplaceInTxBaby(response.getData());

                            // 发送提醒，首页显示红点
                            BaseEvent event = new BaseEvent(BaseEvent.TYPE_NEW_NOTIFICATION);
                            event.setState(1);
                            EventBus.getDefault().post(event);
                        }

                    }, null);
                }
            }

        }, getContext().networkUnavailableSampleImpl());
    }

    /**
     * 上传 MiPush_Token
     */
    public void updateMiPushToken() {
        Logger.d("1");
        LoginInfo loginInfo = Config.getLoginInfo(getContext());
        if (loginInfo == null) {
            return;
        }
        Logger.d("2");
        if (TextUtils.isEmpty(Config.getMiPushId(getContext()))) {
            return;
        }
        Logger.d("3");
        if (Config.getMiPushIdSuccess(getContext())) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        Logger.d("准备推送");
        Client.requestPushToken(getContext(), phone, token, Config.getMiPushId(getContext()), new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                Logger.d("推送成功");
                Config.setMiPushIdSuccess(getContext(), true);
            }

            @Override
            public void onChZhRJFailure(String value) {
                super.onChZhRJFailure(value);
                Logger.d("推送失败");
            }

            @Override
            public void onInnovationExceptionFinish() {
                super.onInnovationExceptionFinish();
                Logger.d("推送超时");
            }
        }, getContext().networkUnavailableSampleImpl());
    }

    /**
     *  设置登录信息
     */
    protected final void setLoginInfo(LoginInfo loginInfo) {
        Gson gson = new Gson();
        String loginValue = gson.toJson(loginInfo);
        Config.setLoginInfo(getContext(), loginValue);
    }

    protected final void insertOrReplaceInTxBabyAndParent(String id, Auth[] auth, int... babyIDArray) {
        DatabaseManager.getInstance(getContext()).insertOrReplaceInTxBabyAndParent(id, auth, babyIDArray);
    }

    protected final void insertOrReplaceInTxBaby(BabyResponse... babyResponses) {
        DatabaseManager.getInstance(getContext()).insertOrReplaceInTxBaby(babyResponses);
    }

    /**
     * 获取宝宝权限
     */
    public BabyAndParent getBabyAndParent(int babyId) {
        if(getContext() == null) {
            return null;
        }
        LoginInfo loginInfo = Config.getLoginInfo(getContext());
        if(loginInfo == null) {
            // 提示重新登录
            getContext().showLogoutDialog();
            return null;
        }
        return DatabaseManager.getInstance(getContext()).queryBabyAndParent(loginInfo.getUserID(), babyId);
    }
}
